<template>
  <a-drawer
    :visible="localVisible"
    title="资源内容"
    :width="600"
    @close="handleClose"
  >
    <div v-if="resource">
      <div style="display: flex; justify-content: space-between; align-items: center;">
      <h3>{{ resource.title }}</h3>
        <a-button danger ghost @click="confirmDeleteResource">
          删除资源
        </a-button>
              </div>
      <p>{{ resource.description }}</p>
      <p><strong>资源类型:</strong> {{ getResourceTypeName(resource.type) }}</p>

      <div style="margin-bottom: 16px;">
        <input
          type="file"
          ref="fileInput"
          @change="handleFileUpload"
          accept=".txt,.pdf,.doc,.docx"
          style="display: none"
        />
        <a-button type="primary" @click="triggerFileInputAndSend" :loading="uploading">
          <a-icon type="upload" /> 上传并发送文件
          </a-button>
      </div>
      <div v-if="selectedFile">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
            <a-button type="link" @click="$emit('deselect-file')">返回文件列表</a-button>
        <div>
            <a-button
              type="primary"
              @click="handleSendToAssistant"
              :loading="sendingMessage"
              style="margin-right: 8px;"
            >
              <a-icon type="message" /> 发送分析请求
            </a-button>
            <a-button danger ghost @click="confirmDeleteFile">
              删除文件
            </a-button>
          </div>
        </div>

        <a-tabs v-model:activeKey="fileActionTab">
          <a-tab-pane key="preview" tab="预览">
              <h4>文件预览: {{ selectedFile.name }}</h4>
              <div v-if="selectedFile.content" style="margin-top: 16px; padding: 16px; background: #f5f5f5; border-radius: 4px;">
                {{ selectedFile.content }}
            </div>
              <FilePreview/>
          </a-tab-pane>

        <a-tab-pane key="edit" tab="编辑">
            <a-spin :spinning="loading">
              <div v-if="formData">
                <json-editor
                  :data="formData"
                  @update:data="formData = $event"
                />
              <div style="text-align: right; margin-top: 16px;">
                <a-button type="primary" @click="handleSave">保存</a-button>
              </div>
            </div>
            <div v-else-if="!loading" style="text-align: center; padding: 20px;">
              <a-empty description="无法加载文件内容" />
            </div>
          </a-spin>
        </a-tab-pane>
      </a-tabs>
    </div>

    <div v-else>
      <a-row :gutter="[16, 16]" style="margin-top: 20px;">
        <a-col :span="6" v-for="file in filteredFiles" :key="file.name">
          <a-card hoverable style="text-align: center; padding: 10px;" @click="$emit('select-file', file)">
            <template #cover>
              <div class="resource-icon">
                <component :is="getIconComponent(resource.type)" style="font-size: 40px;" />
              </div>
            </template>
            <p style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis; width: 100%;">{{ file.name }}</p>
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card hoverable @click="$emit('show-add-file')">
            <div style="font-size: 30px; margin-bottom: 10px;">
              <a-icon type="plus" style="font-size: 40px;"/>
            </div>
            <a-card-meta title="添加新文件" description="点击添加新的文件"/>
          </a-card>
        </a-col>
      </a-row>
    </div>
  </div>
</a-drawer>
</template>

<script>
import FilePreview from "../FilePreview.vue";
import JsonEditor from './JsonEditor.vue';
import { FileOutlined, FileTextOutlined, CalendarOutlined, VideoCameraOutlined } from '@ant-design/icons-vue';
import { Modal, message } from 'ant-design-vue';
import axios from 'axios';

export default {
name: "ResourcePanel",
components: { FilePreview, JsonEditor },
props: {
  visible: { type: Boolean, default: false },
  resource: { type: Object, default: null },
  files: { type: Array, default: () => [] },
  selectedFile: { type: Object, default: null }
},
data() {
  return {
    localVisible: this.visible,
    fileActionTab: "preview",
    formData: null,
    loading: false,
    uploading: false,
    sendingMessage: false,
    currentUser: 'test_user',
    inputs: {
      file: null,
      txt: ''
    },
    fileIcons: {
      transcript: 'file-text',
      video: 'video-camera',
      audio: 'sound',
      image: 'picture',
      document: 'file-word',
      default: 'file'
    },
    resourceTypes: {
      ppt: 'PPT课件',
      transcript: '讲稿',
      plan: '教案',
      media: '多媒体资源'
},
    difyConfig: {
      baseUrl: 'http://localhost/v1',
      apiKey: 'app-ijcvqqiPoXQs3RRyyYzLDOg1',
      endpoints: {
        upload: '/files/upload',
        completion: '/completion-messages'
      }
    }
    };
  },
computed: {
  filteredFiles() {
    if (!this.resource || !this.resource.id) return [];

    return this.files.filter(file =>
      file.resource === this.resource.id &&
      (this.resource.type ? file.type === this.resource.type : true)
    );
  }
  },
watch: {
  visible(newVal) {
    this.localVisible = newVal;
  },
  localVisible(newVal) {
    this.$emit('update:visible', newVal);
  },
  selectedFile: {
    immediate: true,
    handler(newVal) {
      if (newVal && newVal.json_data) {
    this.loadJsonData();
      } else {
        this.formData = null;
  }
}
  }
},
methods: {
  triggerFileInputAndSend() {
    this.$refs.fileInput.click();
  },
  handleFileUpload(event) {
    const file = event.target.files[0];
    if (file) {
      this.inputs.file = file;

      const reader = new FileReader();
      reader.onload = (e) => {
        this.inputs.txt = e.target.result;
        this.sendAnalysisRequest();
};
      reader.readAsText(file);
    }
  },
  sendAnalysisRequest() {
    this.uploading = true;
    const formData = new FormData();
    formData.append('file', this.inputs.file);
    formData.append('query', '请分析这个文件');

    axios.post(`${this.difyConfig.baseUrl}/files/upload`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ${this.difyConfig.apiKey}`
      }
    }).then(response => {
      message.success('文件上传成功');
      this.handleSendToAssistant(response.data.id);
    }).catch(error => {
      console.error('上传失败:', error);
      message.error(`上传失败: ${error.message}`);
    }).finally(() => {
      this.uploading = false;
    });
  },
  handleSave() {
    if (this.formData) {
      console.log('保存的数据:', this.formData);
      this.$emit('save-teaching-plan', this.formData);
      this.$message.success('保存成功');
    }
  },
  loadJsonData() {
    this.loading = true;
    try {
      const jsonData = typeof this.selectedFile.json_data === 'string'
        ? JSON.parse(this.selectedFile.json_data)
        : this.selectedFile.json_data;
      this.formData = jsonData;
    } catch (error) {
      console.error('解析JSON数据失败:', error);
      this.$message.error('解析JSON数据失败: ' + error.message);
    } finally {
      this.loading = false;
    }
  },
  getFileIcon(fileType) {
    return this.fileIcons[fileType] || this.fileIcons.default;
  },
  handleClose() {
    this.localVisible = false;
    this.$emit("close");
  },
  getIconComponent(type) {
    const iconMap = {
      ppt: FileOutlined,
      transcript: FileTextOutlined,
      plan: CalendarOutlined,
      media: VideoCameraOutlined
    };
    return iconMap[type] || FileOutlined;
  },
  getResourceTypeName(type) {
    return this.resourceTypes[type] || '未知类型';
  },
  confirmDeleteResource() {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除资源 "${this.resource?.title}" 吗？`,
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        this.$emit('delete-resource', this.resource.id);
      }
    });
  },
  confirmDeleteFile() {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除文件 "${this.selectedFile?.name}" 吗？`,
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        this.$emit('delete-file', this.selectedFile.id);
      }
    });
  },
  getFileType(filename) {
    const extension = filename.split('.').pop().toLowerCase();
    const documentTypes = ['txt', 'md', 'pdf', 'html', 'xlsx', 'docx', 'csv', 'pptx'];
    const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'];
    const audioTypes = ['mp3', 'm4a', 'wav'];
    const videoTypes = ['mp4', 'mov', 'mpeg'];

    if (documentTypes.includes(extension)) return 'document';
    if (imageTypes.includes(extension)) return 'image';
    if (audioTypes.includes(extension)) return 'audio';
    if (videoTypes.includes(extension)) return 'video';
    return 'document';
  },
  async handleSendToAssistant(fileId) {
    if (!fileId && !this.selectedFile) {
      this.$message.warning('请先选择文件');
      return;
    }

    this.sendingMessage = true;
    try {
      const uploadResponse = fileId ? { id: fileId } : await this.uploadFileToDify({
        file: this.selectedFile,
        onSuccess: (data) => data,
        onError: (error) => {
          throw new Error(`文件上传失败: ${error.message}`);
        }
      });

      const messageResponse = await this.sendChatMessage(uploadResponse.id);

      this.$message.success('分析请求已发送');
      console.log('Dify响应:', messageResponse);

      this.$router.push({
        path: '/chat',
        query: {
          conversation_id: messageResponse.conversation_id,
          file_id: uploadResponse.id
        }
      });

    } catch (error) {
      console.error('发送失败:', error);
      this.$message.error(`发送失败: ${error.message}`);
    } finally {
      this.sendingMessage = false;
    }
  },
  async sendChatMessage(fileId) {
    try {
      this.loading = true;
      const response = await axios.post(`${this.difyConfig.baseUrl}/chat-messages`, {
        query: "请分析这个文件",
        inputs: {
          txt: [{
          type: this.getFileType(this.selectedFile.name),
          transfer_method: "local_file",
          upload_file_id: fileId
        }],
        },
        response_mode: "blocking",
        user: this.currentUser,
        files: [{
          type: this.getFileType(this.selectedFile.name),
          transfer_method: "local_file",
          upload_file_id: fileId
        }],
        auto_generate_name: true
      }, {
        headers: {
          'Authorization': `Bearer ${this.difyConfig.apiKey}`
        }
      });

      message.success('消息发送成功');
      console.log('对话响应:', response.data);
      return response.data;
    } catch (error) {
      console.error('发送消息失败:', error);
      message.error(`发送失败: ${error.message}`);
      throw error;
    } finally {
      this.loading = false;
    }
  }
},
mounted() {
  if (this.selectedFile && this.selectedFile.json_data) {
    this.loadJsonData();
  }
}
};
</script>

<template>
  <a-drawer
    :visible="localVisible"
    title="资源内容"
    :width="600"
    @close="handleClose"
  >
    <div v-if="resource">
      <div style="display: flex; justify-content: space-between; align-items: center;">
      <h3>{{ resource.title }}</h3>
        <a-button danger ghost @click="confirmDeleteResource">
          删除资源
        </a-button>
              </div>
      <p>{{ resource.description }}</p>
      <p><strong>资源类型:</strong> {{ getResourceTypeName(resource.type) }}</p>

      <div v-if="selectedFile">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
            <a-button type="link" @click="$emit('deselect-file')">返回文件列表</a-button>
        <div>
            <a-button type="primary" @click="goToChat" style="margin-right: 8px;">
              发送给小助手
            </a-button>
            <a-button danger ghost @click="confirmDeleteFile">
              删除文件
            </a-button>
          </div>
        </div>

        <a-tabs v-model:activeKey="fileActionTab">
          <a-tab-pane key="preview" tab="预览">
              <h4>文件预览: {{ selectedFile.name }}</h4>
              <div v-if="selectedFile.content" style="margin-top: 16px; padding: 16px; background: #f5f5f5; border-radius: 4px;">
                {{ selectedFile.content }}
            </div>
              <FilePreview/>
          </a-tab-pane>

        <a-tab-pane key="edit" tab="编辑">
            <a-spin :spinning="loading">
              <div v-if="formData">
                <json-editor
                  :data="formData"
                  @update:data="formData = $event"
                />
              <div style="text-align: right; margin-top: 16px;">
                <a-button type="primary" @click="handleSave">保存</a-button>
              </div>
            </div>
            <div v-else-if="!loading" style="text-align: center; padding: 20px;">
              <a-empty description="无法加载文件内容" />
            </div>
          </a-spin>
        </a-tab-pane>
      </a-tabs>
    </div>

    <div v-else>
      <a-row :gutter="[16, 16]" style="margin-top: 20px;">
        <a-col :span="6" v-for="file in filteredFiles" :key="file.name">
          <a-card hoverable style="text-align: center; padding: 10px;" @click="$emit('select-file', file)">
            <template #cover>
              <div class="resource-icon">
                <component :is="getIconComponent(resource.type)" style="font-size: 40px;" />
              </div>
            </template>
            <p style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis; width: 100%;">{{ file.name }}</p>
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card hoverable @click="$emit('show-add-file')">
            <div style="font-size: 30px; margin-bottom: 10px;">
              <a-icon type="plus" style="font-size: 40px;"/>
            </div>
            <a-card-meta title="添加新文件" description="点击添加新的文件"/>
          </a-card>
        </a-col>
      </a-row>
    </div>
  </div>
</a-drawer>
</template>

<script>
import FilePreview from "../FilePreview.vue";
import JsonEditor from './JsonEditor.vue';
import { FileOutlined, FileTextOutlined, CalendarOutlined, VideoCameraOutlined } from '@ant-design/icons-vue';
import { Modal } from 'ant-design-vue';

export default {
name: "ResourcePanel",
components: { FilePreview, JsonEditor },
props: {
  visible: { type: Boolean, default: false },
  resource: { type: Object, default: null },
  files: { type: Array, default: () => [] },
  selectedFile: { type: Object, default: null }
},
data() {
  return {
    localVisible: this.visible,
    fileActionTab: "preview",
    formData: null,
    loading: false,
    fileIcons: {
      transcript: 'file-text',
      video: 'video-camera',
      audio: 'sound',
      image: 'picture',
      document: 'file-word',
      default: 'file'
    },
    resourceTypes: {
      ppt: 'PPT课件',
      transcript: '讲稿',
      plan: '教案',
      media: '多媒体资源'
    }
  };
},
computed: {
  filteredFiles() {
    if (!this.resource || !this.resource.id) return [];

    return this.files.filter(file =>
      file.resource === this.resource.id &&
      (this.resource.type ? file.type === this.resource.type : true)
    );
  }
},
watch: {
  visible(newVal) {
    this.localVisible = newVal;
  },
  localVisible(newVal) {
    this.$emit('update:visible', newVal);
  },
  selectedFile: {
    immediate: true,
    handler(newVal) {
      if (newVal && newVal.json_data) {
        this.loadJsonData();
      } else {
        this.formData = null;
      }
    }
  }
},
methods: {
  handleSave() {
    if (this.formData) {
      console.log('保存的数据:', this.formData);
      this.$emit('save-teaching-plan', this.formData);
      this.$message.success('保存成功');
    }
  },
  loadJsonData() {
    this.loading = true;
    try {
      const jsonData = typeof this.selectedFile.json_data === 'string'
        ? JSON.parse(this.selectedFile.json_data)
        : this.selectedFile.json_data;
      this.formData = jsonData;
    } catch (error) {
      console.error('解析JSON数据失败:', error);
      this.$message.error('解析JSON数据失败: ' + error.message);
    } finally {
      this.loading = false;
    }
  },
  getFileIcon(fileType) {
    return this.fileIcons[fileType] || this.fileIcons.default;
  },
  handleClose() {
    this.localVisible = false;
    this.$emit("close");
  },
  getIconComponent(type) {
    const iconMap = {
      ppt: FileOutlined,
      transcript: FileTextOutlined,
      plan: CalendarOutlined,
      media: VideoCameraOutlined
    };
    return iconMap[type] || FileOutlined;
  },
  getResourceTypeName(type) {
    return this.resourceTypes[type] || '未知类型';
  },
  confirmDeleteResource() {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除资源 "${this.resource?.title}" 吗？`,
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        this.$emit('delete-resource', this.resource.id);
      }
    });
  },
  confirmDeleteFile() {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除文件 "${this.selectedFile?.name}" 吗？`,
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        this.$emit('delete-file', this.selectedFile.id);
      }
    });
  },
  goToChat() {
    this.$router.push('/chat');
    this.localVisible = false;
  }
},
mounted() {
  if (this.selectedFile && this.selectedFile.json_data) {
    this.loadJsonData();
  }
}
};
</script>

